package com.yutianran.springBoot.spider;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownTest {

    private static class ProcessJob implements Runnable {

        private String url;

        public ProcessJob(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            System.out.println(String.format("当前线程：%s 正在处理：%s", Thread.currentThread().getName(), url));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final List<String> list = new ArrayList<String>();
        for (int i = 1; i <= 100; i++) {
            list.add("https://www.zhihu.com/collection/204112305?page=" + i);
        }
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        final CountDownLatch startLatch = new CountDownLatch(1);
        final CountDownLatch stopLatch = new CountDownLatch(list.size());
        for (int i = 0; i < list.size(); i++) {
            final int finalI = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 线程等待开始的Latch
                        startLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        String url = list.get(finalI);
                        new ProcessJob(url).run();
                    } finally {
                        // 调用结束的Latch的countDown
                        stopLatch.countDown();
                    }
                }
            });
        }
        long start = System.currentTimeMillis();
        startLatch.countDown();
        // 等待所有线程执行完任务
        stopLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("Total cost time: " + (end - start));
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
    }
}
